import React, { useState, useRef, useEffect } from 'react';
import Vcode from 'react-vcode';
import { Button, Input, message, Modal } from 'antd';
import { ReloadOutlined, CloseOutlined } from '@ant-design/icons';
import './VcodeCaptcha.scss';

export interface VcodeCaptchaProps {
  open: boolean;
  onClose: () => void;
  onSuccess: (data: any) => void;
  onFail?: (error: any) => void;
  title?: string;
  description?: string;
}

const VcodeCaptcha: React.FC<VcodeCaptchaProps> = ({
  open,
  onClose,
  onSuccess,
  onFail,
  title = '安全验证',
  description = '请输入图片中的验证码',
}) => {
  const [userInput, setUserInput] = useState('');
  const [code, setCode] = useState('');
  const [loading, setLoading] = useState(false);
  const vcodeRef = useRef<any>(null);

  // 当验证码改变时更新code
  const handleCodeChange = (newCode: string) => {
    setCode(newCode);
  };

  // 刷新验证码
  const handleRefresh = () => {
    setUserInput('');
    // 触发验证码重新生成
    if (vcodeRef.current) {
      vcodeRef.current.onClick();
    }
  };

  // 验证用户输入
  const handleVerify = async () => {
    if (!userInput) {
      message.warning('请输入验证码');
      return;
    }

    setLoading(true);
    try {
      // 验证用户输入是否与生成的验证码匹配（不区分大小写）
      const isValid = userInput.toLowerCase() === code.toLowerCase();
      
      if (isValid) {
        message.success('验证成功');
        onSuccess({
          code: 0,
          msg: '验证成功',
          data: {
            sid: 'vcode_sid_' + Date.now(),
            ticket: 'vcode_ticket_' + Date.now(),
          },
        });
        handleClose();
      } else {
        message.error('验证码错误，请重试');
        if (onFail) {
          onFail({ code: 1, msg: '验证码错误' });
        }
        handleRefresh();
      }
    } catch (error) {
      message.error('验证失败，请重试');
      if (onFail) {
        onFail(error);
      }
      handleRefresh();
    } finally {
      setLoading(false);
    }
  };

  // 关闭弹窗
  const handleClose = () => {
    setUserInput('');
    onClose();
  };

  // 按Enter键提交
  const handleKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      handleVerify();
    }
  };

  // 重置状态
  useEffect(() => {
    if (open) {
      setUserInput('');
      handleRefresh();
    }
  }, [open]);

  return (
    <Modal
      open={open}
      title={title}
      onCancel={handleClose}
      footer={null}
      width={400}
      centered
      className="vcode-captcha-modal"
      closeIcon={<CloseOutlined />}
    >
      <div className="vcode-captcha">
        <div className="vcode-description">{description}</div>
        
        <div className="vcode-display">
          <div className="vcode-wrapper">
            <Vcode
              ref={vcodeRef}
              onChange={handleCodeChange}
              width={200}
              height={60}
              length={4}
            />
          </div>
          <Button
            icon={<ReloadOutlined />}
            onClick={handleRefresh}
            className="vcode-refresh-btn"
            title="刷新验证码"
          />
        </div>

        <div className="vcode-input-area">
          <Input
            value={userInput}
            onChange={(e) => setUserInput(e.target.value)}
            onKeyPress={handleKeyPress}
            placeholder="请输入验证码"
            maxLength={4}
            size="large"
            autoFocus
          />
        </div>

        <div className="vcode-actions">
          <Button onClick={handleClose}>取消</Button>
          <Button
            type="primary"
            onClick={handleVerify}
            loading={loading}
          >
            确认
          </Button>
        </div>
      </div>
    </Modal>
  );
};

export default VcodeCaptcha;

